package com.lwhtarena.netty.netty4.server;


import com.lwhtarena.netty.netty4.util.FileInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
 class FixedLengthByteArrayDecoder extends ByteToMessageDecoder {

     private final int frameLength;

     /**
      * Creates a new instance.
      *
      * @param frameLength the length of the frame
      */
     public FixedLengthByteArrayDecoder(int frameLength) {
         if (frameLength <= 0) {
             throw new IllegalArgumentException(
                     "frameLength must be a positive integer: " + frameLength);
         }
         this.frameLength = frameLength;
     }

     @Override
     protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
         Object decoded = decode(ctx, in);
         if (decoded != null) {
             out.add(decoded);
         }
     }

     /**
      * Create a frame out of the {@link ByteBuf} and return it.
      *
      * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
      * @param   in              the {@link ByteBuf} from which to read data
      * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
      *                          be created.
      */
     protected Object decode(
             @SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
         if (in.readableBytes() < frameLength) {
             return null;
         } else {
             return in.readRetainedSlice(frameLength);
         }
     }

}
